/**
 * 附件上传展示
 * @author ex-yujq
 * @version v1.0
 */
//colgroup样式
var colGroups = new Array();
//默认增加列数
var addRowNum = 0;
//增加显示列
var col = new Array();
//标题数组
var row = new Array();
//附件显示样式
var rowValue = new Array();
//附件显示样式字符串
var rowValueStr = '';
//附件上传样式
var rowUploadStr = '';
//新增列取值
var replaceArray = new Array();
//新增列
var columnArray = '';
//附件数据
var attachArray = new Array();
//额外附件数据
var extraAttachArray = new Array();
//附件显示条件
var isShowArray = '';
//附件显示条件隐藏域id
var isShowCondition = '';
//附件显示条件隐藏域取值
var isShowValue = '';
//根据附件属性判断是否显示删除按钮
var isHiddenArray = '';
//附件属性
var isHiddenField = '';
//附件属性值
var isHiddenValue = '';
//遍历隐藏input参数
var loopHidInputParamArray = '';
//上传隐藏input参数
var uploadHidInputParamArray = '';
//修改按钮参数
var modifyButtonParamArray = '';
//显示星图标参数
var showStarIconParamArray = '';
//模块数组
var moduleArray = new Array();
//当前模块
var currentModule = '';
//当前模块附件来源ID
var currentResourceIdValue = '';
//当前模块附件来源标识
var currentResourceSignValue = '';
//当前模块附件来源主体标识
var currentResourceSignModuleValue = '';
//当前模块是否设置权限
var currentIsPermission = '';
//当前模块是否拥有权限
var currentHasPermission = '';
//当前附件ID属性名
var currentHidAttIdField = '';
//复选框样式
var checkboxArray = new Array();
//复选框样式
var checkboxIndex = '';
//复选框样式
var allCheckboxArray = new Array();
//特殊字符
var specialName = "";
var specialNameArray = new Array();
var specialValue = "";
var specialValueArray = new Array();
//上传附件时多选框的模板
var checkBoxTmplt = 0;
//文件类型
var fileType = "";
var fileTypeMap = new Map();
//当前模块存放附件主键id名称
var currentAttId = "";
//当前模块拓展列表列名
var currentHasExpandField ="";
//当前模块拓展下拉列表
var currentHasExpandList ="";
//当前模块是否显示删除按钮
var currentIsOperable = true;
//当前模块需要删除的附件主键
var currentAttDelId = "";

/**
 * 执行
 */
$(function(){
	if(attArr.length > 0){
		//单个文件中引入多次附件上传，对应附件数据只初始化一次
		if(moduleArray.length == 0){
			$.each(attArr, function(index, object){
				//加载特殊字符数据字典
				loadSpecialCharachter();
				//数据初始化
				var colspan = initHtml(object);
				//附件展示
				attachContainer(currentAttId);
				//附件上传
				attachFileUpload(currentAttId);
				//附件删除
				deleteAttachFile(currentAttId,currentAttDelId);
				//模块数组初始化
				moduleArray[index] = currentModule;
				//初始化JS
				attachContainerInitExpandFieldJs();
				
				$("#attachContainer" + currentModule).find(".tipsTd").attr("colspan", colspan);
			});
		}
	}
});

/**
 * 加载特殊字符数据字典和文档分类
 */
function loadSpecialCharachter(){
	$.ajax({
		type : "POST",
		dataType : "json",
		url : ctx + "sys/attach/querySpecialCharacter.do",
		cache: false,
		async: false,
		success: function(data){
			if ("true" == data.status) {
				specialName  = data.specialName;
				specialValue = data.specialValue;
			}
		}
	});
}

/**
 * 数据初始化
 */
function initHtml(object){
	
	//当前模块拓展列表列名
	if(object.hasExpandField && object.hasExpandField.length > 0){
		if(currentModule.length > 0){
			currentHasExpandField = '';
		}
		currentHasExpandField = object.hasExpandField;
	}else{
		currentHasExpandField = '';
	}
	//当前模块拓展下拉列表
	if(object.hasExpandList && object.hasExpandList.length > 0){
		if(currentModule.length > 0){
			currentHasExpandList = '';
		}
		currentHasExpandList = object.hasExpandList;
	}else{
		currentHasExpandList = '';
	}
	//colgroup样式初始化
	colGroups = [
	               //显示附件列表
	               ['<col width="23%"><col width="21%"><col width="13%"><col width="13%"><col width="15%">'],
	               ['<col width="18%"><col width="17%"><col width="13%"><col width="13%"><col width="13%"><col width="13%">'],
	               ['<col width="14%"><col width="14%"><col width="12%"><col width="12%"><col width="12%"><col width="12%"><col width="12%">'],
	               ['<col width="15%"><col width="14%"><col width="10%"><col width="10%"><col width="10%"><col width="10%"><col width="10%"><col width="11%">'],
	               //显示附件列表、删除附件
	               ['<col width="20%"><col width="15%"><col width="15%"><col width="15%"><col width="15%"><col width="8%">'],
	               ['<col width="15%"><col width="10%"><col width="12%"><col width="10%"><col width="10%"><col width="10%"><col width="8%">'],
	               ['<col width="15%"><col width="10%"><col width="10%"><col width="10%"><col width="5%"><col width="5%"><col width="10%"><col width="8%">'],
	               ['<col width="12%"><col width="10%"><col width="10%"><col width="10%"><col width="10%"><col width="10%"><col width="10%"><col width="10%"><col width="8%">']
	            ];
	
	//附件标题初始化
	row = [
		['<td>附件名称</td>'],
		['<td>附件来源</td>'],
		['<td>附件状态</td>'],
		['<td>上传人员</td>'],
		['<td>上传时间</td>']
		];
	//添加拓展列
	var expandFieldsLen = 0;
	if(currentHasExpandField && currentHasExpandField.length > 0){
		var expandFields = eval('(' + currentHasExpandField + ')');
		expandFieldsLen = expandFields.length;
		var fieldName = "";
		var index = row.length / 2;
		$.each(expandFields,function(i,data){
			fieldName = data.fieldName;
			row.splice(index+i, 0, ['<td>'+fieldName+'</td>']);
		});
	}
	
	//显示附件数据模板
	rowValue = [
	 	         ["<tr class='uploaded' id='{{attachId}}'>"],
	 	         ["<input type='hidden' name='attId' id='attId' value='{{attachId}}'/>"],
	 	           ["<td><a style='color:#000000;text-decoration:underline;' href='{{path}}sys/attach/downloadAttach.do?attId={{attachId}}' target='_blank' name='attName'>{{attachName}}</a></td>"],
	 	           ["<td>{{resourceSignName}}</td>"],
	 	           ["<td>{{status}}</td>"],
	 	           ["<td>{{createName}}</td>"],
	 	           ["<td>{{createTime}}</td>"],
	 	         ["</tr>"]
		       ];
	if(currentHasExpandField && currentHasExpandField.length > 0){
		var expandFields = eval('(' + currentHasExpandField + ')');
		var expandLists = eval('(' + currentHasExpandList + ')');
		var fieldKey = "";
		var fieldName = "";
		var index = rowValue.length / 2;
		$.each(expandFields,function(i,data){
			fieldKey = data.fieldKey;
			fieldName = data.fieldName;
			var expandList = expandLists[i];
			var expandColInput = "<input type='hidden' id='" + fieldKey + "ExtId{{attachId}}' name='" + fieldKey + "ExtId{{attachId}}' value='{{" + fieldKey + "ExtId}}'/>";
			var expandColSelectStart = "<select class='form-control use-select2' placeholder='"+fieldName+"' name='"+fieldKey+"{{attachId}}' id='"+fieldKey+"{{attachId}}'>";
			var expandColOption = "<option value=''></option>";
			var expandColSelectEnd = "</select>";
			$.each(expandList,function(j,data){
				expandColOption = expandColOption + "<option value='"+data.dctValue+"'>"+data.dctName+"</option>";
			});
			var expandColSelectTag = expandColSelectStart + expandColOption + expandColSelectEnd;
			rowValue.splice(index+i, 0, ['<td>' + expandColInput + expandColSelectTag + '</td>']);
		});
	}
	//多选框初始化
	checkboxArray = [
	                    ["<input type='checkbox' name='chkAttach' atid='0' id='chkAttach{{attachId}}' value='{{attachId}}'/>"],
	                    ["<input type='checkbox' checked='checked' name='chkAttach' atid='0' id='chkAttach{{attachId}}' value='{{attachId}}' onclick='return false'/>"]
	                ]; 
	
	//全选按钮初始化
	allCheckboxArray = [
	                       ["<td><input style='vertical-align:middle; margin-top:-2px; margin-bottom:1px;' type='checkbox' id='chkifAll' name='chkifAll'/>&nbsp;&nbsp;全选</td>"]
	                   ];
	
	//文件类型
	fileTypeMap.put("pdf", "application/pdf")
			   .put("doc", "application/msword")
			   .put("zip", "application/zip")
			   .put("png", "image/png")
			   .put("jpg", "image/jpeg")
			   .put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
			   .put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
	
	//特殊符号转换为字符数组
	if(specialName.length > 0 && specialValue.length > 0){
		specialNameArray = specialName.split(",");
		specialValueArray = specialValue.split(",");
	}
	
	//附件数据转为对象
	if(object.attachList && object.attachList.length > 0){
		var tempStr = object.attachList;
		if(attachArray.length > 0){
			attachArray = '';
		}
		//特殊字符转换
		if(specialNameArray.length > 0 && specialValueArray.length > 0){
			for(var i=0; i<specialNameArray.length; i++){
				if(tempStr.indexOf(specialValueArray[i]) > 0){
					tempStr = tempStr.replace(new RegExp(specialValueArray[i],'g'), specialNameArray[i]);
				}
			}
		}
		attachArray = JSON.parse(tempStr);
	}else{
		attachArray = '';
	}
	
	//附件额外数据转为对象
	if(object.extraList && object.extraList.length > 0){
		if(attachArray.length > 0){
			extraAttachArray = '';
		}
		extraAttachArray = JSON.parse(object.extraList);
	}else{
		extraAttachArray = '';
	}
	
	//新增列参数转为对象
	if(object.columns && object.columns.length > 0){
		if(columnArray.length > 0){
			columnArray = '';
		}
		columnArray = JSON.parse(object.columns);
	}else{
		columnArray = '';
	}
	
	//根据附件属性判断是否显示删除按钮
	if(object.isHidden && object.isHidden.length > 0){
		if(isHiddenArray.length > 0){
			isHiddenArray = '';
		}
		isHiddenArray = JSON.parse(object.isHidden);
		//仅支持一个属性
		isHiddenValue = isHiddenArray[0].value;
		isHiddenField = isHiddenArray[0].field;
	}else{
		isHiddenArray = '';
	}
	
	//附件显示条件
	if(object.isShow && object.isShow.length > 0){
		if(isShowArray.length > 0){
			isShowArray = '';
			isShowCondition = '';
			isShowValue = '';
		}
		isShowArray = JSON.parse(object.isShow);
		//仅支持一个条件
		isShowCondition = $("#" + isShowArray[0].id).val();
		isShowValue = isShowArray[0].value;
	}else{
		isShowArray = '';
		isShowCondition = '';
		isShowValue = '';
	}
	
	//遍历隐藏input参数数据类型转换
	if(object.loopHidInputParams && object.loopHidInputParams.length > 0){
		if(loopHidInputParamArray.length > 0){
			loopHidInputParamArray = '';
		}
		loopHidInputParamArray = JSON.parse(object.loopHidInputParams);
	}else{
		loopHidInputParamArray = '';
	}
	
	//上传隐藏input参数数据类型转换
	if(object.uploadHidInputParams && object.uploadHidInputParams.length > 0){
		if(uploadHidInputParamArray.length > 0){
			uploadHidInputParamArray = '';
		}
		uploadHidInputParamArray = JSON.parse(object.uploadHidInputParams);
	}else{
		uploadHidInputParamArray = '';
	}
	
	//显示星图标
	if(object.showStarIconParam && object.showStarIconParam.length > 0){
		if(showStarIconParamArray.length > 0){
			showStarIconParamArray = '';
		}
		showStarIconParamArray = JSON.parse(object.showStarIconParam);
	}else{
		showStarIconParamArray = '';
	}
	
	//当前模块
	if(object.module && object.module.length > 0){
		if(currentModule.length > 0){
			currentModule = '';
		}
		currentModule = object.module;
	}else{
		currentModule = '';
	}
	
	//当前模块是否设置权限
	if(object.isPermission && object.isPermission.length > 0){
		if(currentIsPermission.length > 0){
			currentIsPermission = '';
		}
		currentIsPermission = object.isPermission;
	}else{
		currentIsPermission = '';
	}
	//当前模块是否拥有权限
	if(object.hasPermission){
		if(currentHasPermission.length > 0){
			currentHasPermission = '';
		}
		currentHasPermission = object.hasPermission;
	}else{
		currentHasPermission = '';
	}
	if("true" == object.defaultPermission){
		currentHasPermission = true;
	}
	
	//当前附件来源ID
	if(object.resourceIdValue && object.resourceIdValue.length > 0){
		if(currentResourceIdValue.length > 0){
			currentResourceIdValue = '';
		}
		currentResourceIdValue = object.resourceIdValue;
	}else{
		currentResourceIdValue = '';
	}
	
	//当前附件来源标识
	if(object.resourceSignValue && object.resourceSignValue.length > 0){
		if(currentResourceSignValue.length > 0){
			currentResourceSignValue = '';
		}
		currentResourceSignValue = object.resourceSignValue;
	}else{
		currentResourceSignValue = '';
	}
	
	//当前附件来源主体标识
	if(object.resourceSignModuleValue && object.resourceSignModuleValue.length > 0){
		if(currentResourceSignModuleValue.length > 0){
			currentResourceSignModuleValue = '';
		}
		currentResourceSignModuleValue = object.resourceSignModuleValue;
	}else{
		currentResourceSignModuleValue = '';
	}
	
	//当前附件ID属性名
	if(object.hidAttIdField && object.hidAttIdField.length > 0){
		if(currentHidAttIdField.length > 0){
			currentHidAttIdField = '';
		}
		currentHidAttIdField = object.hidAttIdField;
	}else{
		currentHidAttIdField = '';
	}
	
	//当前附件ID属性名
	if(object.checkbox && object.checkbox.length > 0){
		if(checkboxIndex.length > 0){
			checkboxIndex = '';
		}
		checkboxIndex = object.checkbox;
		if (object.checkBoxTmplt && object.checkBoxTmplt > 0) {
			checkBoxTmplt = object.checkBoxTmplt;
		}
	}else{
		checkboxIndex = '';
	}
	
	//文件上传类型入参
	if(object.file && object.file.length > 0){
		if(fileType.length > 0){
			fileType = '';
		}
		fileType = object.file.toLowerCase();
	}else{
		fileType = '';
	}
	
	//模块唯一标识
	$("#attachContainer").attr("id", "attachContainer" + currentModule);
	$("#attach-file-upload").attr("id", "attach-file-upload" + currentModule);
	
	var colspan = 4;
	if(expandFieldsLen != 0) {
		var cs = $("#attachContainer" + currentModule).find(".tipsTd").attr("colspan");
		colspan = cs*1 + expandFieldsLen;
	}
	
	
	//当前模块存放附件主键ID名称
	if(object.module && object.module.length > 0){
		if(currentAttId.length > 0){
			currentAttId = '';
		}
		currentAttId = 'attIds' + object.module;
	}else{
		currentAttId = $("#attIds").attr("id");
	}
	//设置附件主键集合ID
	$("#attIds").attr("id", currentAttId);
	
	//当前模块存放附件主键ID名称
	if(object.module && object.module.length > 0){
		if(currentAttDelId.length > 0){
			currentAttDelId = '';
		}
		currentAttDelId = 'attDelIds' + object.module;
	}else{
		currentAttDelId = $("#attDelIds").attr("id");
	}
	
	
	if(object.hidAttNameField) {
		$("#attIds").attr("name", object.hidAttNameField);
	}

	//设置附件删除主键集合ID
	$("#attDelIds").attr("id", currentAttDelId);
	
	//当前模块控件是否可操作
	if(object.isOperable && object.isOperable.length > 0){
		var isisOperableJson = eval('(' + object.isOperable + ')');
		if(currentIsOperable == false){
			currentIsOperable = true;
		}
		var isOperable = isisOperableJson.isOperable;
		if("false" == isOperable){
			currentIsOperable = false;
		}
	}
	
	return colspan;
}
/**
 * 初始化js
 * @returns
 */
function initJs(attachId){
	//设置拓展字段下拉列表样式
	if(currentHasExpandField && currentHasExpandField.length > 0){
		var expandFields = eval('(' + currentHasExpandField + ')');
		var fieldKey = "";
		var fieldName = "";
		$.each(expandFields,function(i,data){
			fieldKey = data.fieldKey;
			fieldName = data.fieldName;
			$('*[name="'+fieldKey+attachId+'"]').select2({placeholder: fieldName});
			if(!currentIsOperable){
				$('#'+fieldKey+attachId).attr("disabled","disabled");
			}
			
		});
	}
}
/**
 * 附件展示
 */
function attachContainer(){
	//是否增加列
	if(columnArray.length > 0){
		addRowNum = columnArray.length;
	}
	//默认隐藏附件上传
	var $widget = $("#" + "attachContainer" + currentModule +" .attachUploadWidget");
	$widget.hide();
	//显示上传控件显示条件
	if(isShowArray.length == 1){
		if(isShowCondition == isShowValue){
			//是否设置权限
			if(currentIsPermission.length > 0){
				if(true == currentHasPermission){
					$widget.show();
				}
			}
		}
	}else{
		if(currentIsPermission.length > 0){
			if(true == currentHasPermission){
				$widget.show();
			}
		}
	}
	matchColGroup('#attachContainer' + currentModule);
	//附件展示及上传
	if(attachArray.length > 0){
		if(checkboxIndex.length > 0){
			rowValue.splice(1, 0, "<td>" + checkboxArray[checkboxIndex] + "</td>");
		}
		$.each(attachArray, function (index, attach) {
			//附件展示列数组转化为字符串
			rowValueStr = addLoopHiddenInputParams(rowValue.join(''));
			updateHidAttId(currentAttId,attach.attId);
			
			//是否属于当前模块
			rowValueStr = isCurrentMoudle(rowValueStr, attach.resourceSign);
			$('#attachContainer' + currentModule).append(replacerowValueStr(rowValueStr, attach));
		});
		
		if(extraAttachArray.length > 0){
			$.each(extraAttachArray, function (index, att) {
				//附件展示列数组转化为字符串
				rowValueStr = addLoopHiddenInputParams(rowValue.join(''));
				//是否属于当前模块
				rowValueStr = isCurrentMoudle(rowValueStr, att.resourceSign);
				$('#attachContainer' + currentModule).append(replacerowValueStr(rowValueStr, att));
			});
		}
	//新建功能没有历史附件
	}else{
		//附件数据记录为空
	}
};
/**
 * 初始化附件展示列表页拓展字段初始化对应属性js
 * @returns
 */
function attachContainerInitExpandFieldJs(){
	$.each(attachArray, function (index, attach) {
		initJs(attach.attId);
	});
}

/**
 * 打开附件所属详情界面
 * @param resourceId
 * @param resourceSign
 */
function openAttachResourceDetail(resourceId, resourceSign){
	if (resourceId != "" && resourceId != undefined && resourceSign != "" && resourceSign != undefined) {
		var url = ctx + "sys/attach/attachResourceDetail.do?resourceId=" + resourceId + "&resourceSign=" + resourceSign;
		openDialog(url);
	}
}

/**
 * 判断是否属于当前模块
 * @param sign
 */
function isCurrentMoudle(str, sign){
	if(currentResourceSignValue.length > 0){
		var attachResourceSign = $.trim(sign);
		var sign = $.trim(currentResourceSignValue);
		if(attachResourceSign && sign && attachResourceSign == sign){
//			str = str.replace("class='uploaded'", "class='uploaded' style='background-color:#BFE9F9;'");
			str = str.replace("class='uploaded'", "class='uploaded'");
		}
	}
	return str;
}

/**
 * 附件文件删除，并移除显示
 */
function deleteAttachFile(currentAttId,currentAttDelId){
	//删除上传成功附件
	$('#attachContainer' + currentModule).on('click', '.uploaded .f-delete', function() {
		var $tr = $(this).parents('tr[class*=uploaded]');
	    var	attachId = $tr.attr("id");
		ctools.confirm({
			title : "确认删除附件？",
			text : ""
		}, function(isConfirm) {
			if (isConfirm) {
				if (attachId != undefined || attachId != null){
					ctools.alert_sweet("删除附件成功！", 'success', '');
					deleteHidAttId(currentAttId,currentAttDelId,attachId);
					$tr.remove();
					
					
//					$.ajax({
//						type : "GET",
//						cache : false,
//						ifModified : true,
//						dataType : "json",
//						url : ctx + 'sys/attach/delAttachInfo.do?attId=' + attachId,
//						success : function(data) {
//							if('1' == data.state){
//								ctools.alert_sweet('删除失败！','error',data.stateMsg);
//							}else{
//								if('1' == data.isOK){
//									ctools.alert_sweet("删除附件成功！", 'success', '');
//									deleteHidAttId(currentAttId,attachId);
//									$tr.remove();
//								} else{
//									ctools.alert_sweet("删除附件失败！", 'error',  data.msg);
//								}
//							}
//						},
//						error : function(jqXHR, textStatus, errorThrown) {
//							ctools.alert_sweet("删除附件数据错误！", 'error', textStatus);
//						}
//					});
				}
			}
		});
	});
	//删除上传失败附件
	$('#attachContainer' + currentModule).on('click', '.upload-error .f-delete', function() {
		$(this).parents('tr[class*=upload-error]').remove();
	});
}

/**
 * 匹配显示行与对应显示样式
 * @param tableName
 */
function matchColGroup(tableName){
	//是否添加额外显示条件
	if(isShowArray.length == 1){
		if(isShowCondition == isShowValue){
			//是否设置权限
			if(currentIsPermission.length > 0){
				if(true == currentHasPermission){
					//添加列大于3行时，取消列宽适配，浏览器默认列宽
					if(checkboxIndex.length > 0 || addRowNum > 3){
						$(tableName + '').children('colgroup').remove();
					}else{
						//获取样式布局
						$(tableName + '').children('colgroup').html(colGroups[addRowNum + row.length] - 1);
					}
				}
			}else{
				//添加列大于3行时，取消列宽适配，浏览器默认列宽
				if(checkboxIndex.length > 0 || addRowNum > 3){
					$(tableName + '').children('colgroup').remove();
				}else{
					//获取样式布局
					$(tableName + '').children('colgroup').html(colGroups[addRowNum]);
				}
			}
			//设置上传附件按钮靠右
			$(tableName + ' tbody tr td').eq(1).attr("colspan", addRowNum + checkboxIndex.length + 4);
		}else{
			if(checkboxIndex.length > 0 || addRowNum > 3){
				$(tableName + '').children('colgroup').remove();
			}else{
				$(tableName + '').children('colgroup').html(colGroups[addRowNum]);
			}
			//设置上传附件按钮靠右
			$(tableName + ' tbody tr td').eq(1).attr("colspan", addRowNum + checkboxIndex.length + 4);
		}
	}else{
		//是否设置权限
		if(currentIsPermission.length > 0){
			//拥有权限
			if(true == currentHasPermission){
				//添加列大于3行时，取消列宽适配，浏览器默认列宽
				if(checkboxIndex.length > 0 || addRowNum > 3){
					$(tableName + '').children('colgroup').remove();
				}else{
					$(tableName + '').children('colgroup').html(colGroups[addRowNum + row.length - 1]);
				}
				$(tableName + ' tbody tr td').eq(1).attr("colspan", addRowNum + checkboxIndex.length + 4);
			}
		}else{
			if(checkboxIndex.length > 0 || addRowNum > 3){
				$(tableName + '').children('colgroup').remove();
			}else{
				$(tableName + '').children('colgroup').html(colGroups[addRowNum]);
			}
			$(tableName + ' tbody tr td').eq(1).attr("colspan", addRowNum + checkboxIndex.length + 4);
		}
	}
	matchRow(tableName);
}

/**
 * 匹配相应的表头和数据行格式
 * @param tableName
 */
function matchRow(tableName){
	var deleteColStr = "<td>操作列表</td>";
	var deleteStr = "<td><a style='display:inline;' href='#' title='删除附件' class='btn btn-link btn-jqgrid f-delete' data-toggle='modal' data-target='#modal-info' name='attDelBtn'>删除</a></td>";
	//增加显示操作列表表头
	if(isShowArray.length == 1){
		//增加额外显示条件，且条件满足
		if(isShowCondition == isShowValue){
			//是否设置权限
			if(currentIsPermission.length > 0){
				//拥有权限
				if(true == currentHasPermission){
					if(checkboxIndex.length > 0){
						row.splice(0, 0, allCheckboxArray[checkboxIndex]);
					}
					if(!currentIsOperable){
						deleteStr = "<td></td>";
					}
					row.splice(row.length, 0, deleteColStr);
					rowValue.splice(rowValue.length - 1, 0, deleteStr);
				}
			}else{
				if(checkboxIndex.length > 0){
					row.splice(0, 0, allCheckboxArray[checkboxIndex]);
				}
			}
		}else{
			if(checkboxIndex.length > 0){
				row.splice(0, 0, allCheckboxArray[checkboxIndex]);
			}
		}
	}else{
		//是否设置权限
		if(currentIsPermission.length > 0){
			//拥有权限
			if(true == currentHasPermission){
				if(checkboxIndex.length > 0){
					row.splice(0, 0, allCheckboxArray[checkboxIndex]);
				}
				if(!currentIsOperable){
					deleteStr = "<td></td>";
				}
				row.splice(row.length, 0, deleteColStr);
				rowValue.splice(rowValue.length - 1, 0, deleteStr);
			}
		}else{
			if(checkboxIndex.length > 0){
				row.splice(0, 0, allCheckboxArray[checkboxIndex]);
			}
		}
	}
	//额外添加的显示列赋值
	if(addRowNum && 0 != addRowNum){
		$.each(columnArray, function(index, column){
			if(checkboxIndex.length > 0){
				row.splice(parseInt(column.position), 0, '<td>' + column.title + '</td>');
			}else{
				row.splice(parseInt(column.position) - 1, 0, '<td>' + column.title + '</td>');
			}
			rowValue.splice(parseInt(column.position), 0, '<td>' + column.value + '</td>');
			//列取值是否来自后台数据
			if(-1 != column.value.indexOf("{{") && -1 != column.value.indexOf("}}")){
				replaceArray[index] = column.value;
			}
		});
	}
	//显示附件标题
	$(tableName + ' .attachTitle').html(row.join(''));
	//上传样式赋初始化
	rowUploadStr = addUploadHiddenInputParams(rowValue.join(''));
	//附件上传取消跳转详情
	rowUploadStr = rowUploadStr.replace("onclick='openAttachResourceDetail(\"{{resourceId}}\", \"{{resourceSign}}\");'", "");
}

/**
 * 遍历模板中添加input隐藏域
 */
function addLoopHiddenInputParams(loopStr){
	var inputTag = "<input type='hidden' name='{{name}}' id='{{id}}' value='{{value}}'/>";
	var replaceInputTag = '';
	//是否需要添加隐藏域
	if(loopHidInputParamArray.length > 0){
		$.each(loopHidInputParamArray, function(index, object){
			replaceInputTag = replaceInputTag + inputTag.replace('{{name}}', object.hidName).replace('{{id}}', object.hidId).replace('{{value}}', object.hidValue);
		});
		loopStr = loopStr.replace('{{status}}', '{{status}}' + replaceInputTag);
	}
	return loopStr;
}

/**
 * 上传模板中添加input隐藏域
 */
function addUploadHiddenInputParams(uploadStr){
	if(checkboxIndex.length > 0){
		//根据传过来的下标选择checkBox的模板
		var checkBoxTr = "<tr class='uploaded' id='{{attachId}}'>" + "<td>" + checkboxArray[checkBoxTmplt] + "</td>";
		uploadStr = uploadStr.replace("<tr class='uploaded' id='{{attachId}}'>", checkBoxTr);
	}
	var inputTag = "<input type='hidden' name='{{name}}' id='{{id}}' value='{{value}}'/>";
	var replaceInputTag = '';
	
	//是否需要添加隐藏域
	if(uploadHidInputParamArray.length > 0){
		$.each(uploadHidInputParamArray, function(index, object){
			replaceInputTag = replaceInputTag + inputTag.replace('{{name}}', object.hidName).replace('{{id}}', object.hidId).replace('{{value}}', object.hidValue);
		});
		uploadStr = uploadStr.replace('{{status}}', '{{status}}' + replaceInputTag);
	}
	
	//添加额外显示列，添加默认值
	if(columnArray.length > 0){
		$.each(columnArray, function(index, object){
			if(uploadStr.indexOf(object.value) > 0){
				uploadStr = uploadStr.replace(object.value, object.defaultValue);
			}
		});
	}
	
	//发起签报模块
	if(checkboxIndex.length > 0 && uploadStr.indexOf("atid='0'")){
		uploadStr = uploadStr.replace("atid='0'", "atid='1'");
	}
	return uploadStr;
}

/**
 * 替换操作按钮
 * @param operateStr 操作字符串
 * @param newStr 替换内容
 * @param startTag 开始标签
 * @param endTag 结束标签
 */
function replaceOperateButton(operateStr, newStr, startTag, endTag){
	var startIndex = rowUploadStr.lastIndexOf(startTag) + startTag.length;
	var endIndex = rowUploadStr.lastIndexOf(endTag);
	var subStr = operateStr.substring(startIndex, endIndex);
	return operateStr.replace(subStr, newStr);
}

/**
 * 替换附件行数据
 * @param valueStr
 * @param attach
 */
function replacerowValueStr(str, attach){
	var attachAttr = "";
	var loopAttr = "";
	//是否传入columns
	if(replaceArray.length > 0){
		//使用后台数据替换添加的列
		$.each(replaceArray, function(index, object){
			attachAttr = replaceArray[index].replace('{{','').replace('}}','');
			for(var i in attach){
				//传入的属性名与后台数据属性名匹配
				if(attachAttr == i){
					str = str.replace(new RegExp(replaceArray[index],'g'), attach[i]);
				}
			}
		});
	}
	
	//替换遍历隐藏域中input的value取值为附件属性值
	if(loopHidInputParamArray.length > 0){
		$.each(loopHidInputParamArray, function(index, object){
			//隐藏域中的取值为附件属性
			if(-1 != object.hidValue.indexOf("{{") && -1 != object.hidValue.indexOf("}}")){
				loopAttr = object.hidValue.replace('{{','').replace('}}','');
				for(var i in attach){
					//传入的属性名与后台数据属性名匹配
					if(loopAttr == i){
						str = str.replace(new RegExp(object.hidValue,'g'), attach[i]);
					}
				}
			}
		});
	}
	

	//是否添加修改按钮
	if(modifyButtonParamArray.length > 0){
		var modifyParam = modifyButtonParamArray[0];
		var firstField = modifyParam.firstField.replace('{{','').replace('}}','');
		var secondField = modifyParam.secondField.replace('{{','').replace('}}','');
		var deleteButtonStr = "<a style='display:inline;' href='#' title='删除附件' class='btn btn-link btn-jqgrid f-delete' data-toggle='modal' data-target='#modal-info' name='attDelBtn'>删除</a>";
		var firstModifyButtonStr = "<a style='display:inline;' href='#' onclick='OpenModifyContract(\"{{attachId}}\")' class='btn btn-link btn-jqgrid' title='修改' data-toggle='modal' data-target='#modal-info'>修改</a>";
		var secondModifyButtonStr = "<a style='display:inline;' href='#' class='btn btn-link btn-jqgrid' title='修改' data-toggle='modal' data-target='#modal-info' disabled='disabled'>修改</a>";
		//第一次条件判断
		for(var i in attach){
			if(firstField == i){
				if(modifyParam.firstValue == attach[i]){
					//第二次条件判断
					for(var j in attach){
						if(secondField == j){
							if(modifyParam.secondValue == attach[j]){
								str = str.replace(deleteButtonStr, deleteButtonStr + firstModifyButtonStr);
							}else{
								str = str.replace(deleteButtonStr, deleteButtonStr + secondModifyButtonStr);
							}
						}
					}
				}
			}
		}
	}
		
	//是否传入isHidden
	if(isHiddenArray.length == 1){
		for(var i in attach){
			//isHidden属性名与附件属性名匹配
			if(isHiddenField == i){
				if(isHiddenValue == attach[i]){
					str = str.replace("<a style='display:inline;' href='#' title='删除附件' class='btn btn-link btn-jqgrid f-delete' data-toggle='modal' data-target='#modal-info' name='attDelBtn'>删除</a>", '');
				}
			}
		}
	}
	
	//是否显示星图标
	if(showStarIconParamArray.length == 1){
		var starField = showStarIconParamArray[0].field.replace('{{','').replace('}}','');
		var starValue = showStarIconParamArray[0].value.replace('{{','').replace('}}','');
		var starStr = "<span class='text-danger'>★</span>&nbsp;&nbsp;";
		for(var i in attach){
			if(starField == i){
				if(starValue == attach[i]){
					str = str.replace("{{attachName}}", starStr + "{{attachName}}");
				}
			}
		}
	}
	
	//替换附件ID属性名
	if(currentHidAttIdField.length > 0){
		var tempStr = currentHidAttIdField.replace('{{','').replace('}}','');
		for(var i in attach){
			if(tempStr == i){
				str = str.replace(new RegExp(currentHidAttIdField,'g'), attach[i])
				         .replace(new RegExp('{{attachId}}','g'), attach[i]);
			}
		}
	}
	
	//替换拓展列属性名
	if(currentHasExpandField && currentHasExpandField.length > 0){
		var expandFields = eval('(' + currentHasExpandField + ')');
		var expandFieldExtId = "";
		$.each(expandFields,function(i,data){
			expandFieldExtId = "extId";
			for(var i in attach){
				if(expandFieldExtId == i){
					expandFieldExtId = data.fieldKey + "ExtId";
					str = str.replace(new RegExp('{{'+ expandFieldExtId +'}}','g'), attach[i]);
				}
			}
		});
	}
	//选中默认值
	if(currentHasExpandField && currentHasExpandField.length > 0){
		var expandFields = eval('(' + currentHasExpandField + ')');
		var expandFieldSelected = "";
		var selectedValue = "";
		var startIndex = 0;
		var endIndex = 0;
		var regExpStr = "";
		var replaceStr = "";
		$.each(expandFields,function(i,data){
			expandFieldSelected = data.fieldKey + "Selected";
			selectedValue = attach["attrValue"];
			regExpStr = "<option value='" + selectedValue + "'>";
			replaceStr = "<option value='" + selectedValue + "' selected=selected >";
			startIndex = str.indexOf(regExpStr);
			endIndex = startIndex + regExpStr.length;
			
			console.log(str.substring(startIndex,endIndex));
			
			if(startIndex > 0){
				str = str.replace(new RegExp(regExpStr,'g'), replaceStr);
			}
			console.log(str);
			
		});
	}
	
	
	
	return str.replace(new RegExp('{{attachId}}','g'), attach.attId)
           .replace(new RegExp('{{path}}','g'), ctx)
           .replace('{{attachName}}', attach.attName)
           .replace('{{resourceSignName}}', attach.resourceSignName)
           .replace('{{resourceSign}}', attach.resourceSign)
           .replace('{{status}}', '已上传')
           .replace('{{createName}}', attach.createName)
           .replace('{{createTime}}', attach.createTime);
}

/**
 * 附件上传
 */
function attachFileUpload(currentAttId){
	$('#attach-file-upload' + currentModule).upload({
		url : ctx+'sys/attach/uploadFile4Create.do',
		container : '#attachContainer' + currentModule,
		// 可见最大可上传大小，可选
		size : 31457280,
	    //是否多文件上传
        multiple: true,
		//可选参数
        data: {resourceSign : currentResourceSignValue},
        //文件类型
        type: (fileType == null || fileType == '') ? null : fileTypeMap.data[fileType],
        typeMessage: (fileType == null || fileType == '') ? null : "请上传 " + fileType + " 文件",
        //上传失败
        loadingPreview: function(f) {
        	return replaceOperateButton(rowUploadStr, "<a href='javascript:void(0)' title='取消上传' class='btn btn-link btn-jqgrid f-cancel'><i class='fa fa-reply'></a>", '<td>', '</td>')
                   .replace(new RegExp('{{attachId}}','g'), '')
                   .replace('{{path}}', ctx)
                   .replace('uploaded', 'uploading')
                   .replace("<tr", "<tr style='background-color:#FFFFCC'")
                   .replace('{{attachName}}', f.name)
                   .replace('{{resourceSignName}}', '')
                   .replace('{{status}}', '正在上传...<span class="f-progress">0</span>%')
                   .replace('{{createName}}', current_name)
                   .replace('{{createTime}}', dateFormat());
        },
        donePreview: function(f) {
			debugger;
        	if (f.isOK == 'success') {
            	updateHidAttId(currentAttId,f.id);
        		return rowUploadStr
     	       .replace(new RegExp('{{attachId}}','g'), f.id)
               .replace('{{path}}', ctx)
//               .replace("<tr", "<tr style='background-color:#BFE9F9'")
               .replace('{{attachName}}', f.name)
               .replace('{{resourceSignName}}', f.resourceSignName)
               .replace('{{status}}', '已上传')
               .replace('{{createName}}', current_name)
               .replace('{{createTime}}', dateFormat());
        	} else {
        		ctools.alert("文件上传失败", f.errorMessage, "error");
        	}
        },
        failPreview: function(f) {
        	ctools.alert("文件上传失败", f.errorMessage, "error");
        },
        doneCall: function (result){
        	initJs(result.id);
        },
		showError : function(e) {
			ctools.alert("文件上传失败", e.msg,"error");
		}
	});
}


/**
 * 将上传的附件id存入隐藏域中
 */
function updateHidAttId(idName,attId){
	console.log(idName);
	var attIds = $("#"+idName).val();
	if(attIds.length == 0){
		$("#"+idName).val(attId);
	}else{
		$("#"+idName).val(attIds + "," + attId);
	}
}


/**
 * 若删除附件为当前上传的附件，将对应的附件id从隐藏域中删除
 * @param attachId
 */
function deleteHidAttId(attIdName,attDelIdName,attachId){
	var attIds = $("#"+attIdName).val();
	var index = attIds.indexOf(attachId);
	var subStr = attIds;
	//当前仅上传了一个文件
	if(attIds.indexOf(",") < 0){
		subStr = attIds.replace(attachId, "");
	}else{
		if(index == 0){
			subStr = attIds.replace(attachId + ",", "");
		}else if(index > 0){
			subStr = attIds.replace("," + attachId, "");
		}else{
			//改附件不属于当前上传的附件，不作处理
		}
	}
	$("#"+attIdName).val(subStr);
	var attDelIds = $("#"+attDelIdName).val();
	
	if(attDelIds.length == 0){
		$("#"+attDelIdName).val(attachId);
	}else{
		$("#"+attDelIdName).val(attDelIds + "," + attachId);
	}
}

/**
 * 日期格式转换
 * @param format
 * @param date
 * @returns {String}
 */
function dateFormat(format, date) {
	date = date ? new Date(date) : new Date;
	format = format || 'yyyy/MM/dd hh:mm:ss';
	var map = {
		"M" : date.getMonth() + 1, // 月份
		"d" : date.getDate(), // 日
		"h" : date.getHours(), // 小时
		"m" : date.getMinutes(), // 分
		"s" : date.getSeconds(), // 秒
		"q" : Math.floor((date.getMonth() + 3) / 3), // 季度
		"S" : date.getMilliseconds() // 毫秒
	};
	format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
		var v = map[t];
		if (v !== undefined) {
			if (all.length > 1) {
				v = '0' + v;
				v = v.substr(v.length - 2);
			}
			return v;
		} else if (t === 'y') {
			return (date.getFullYear() + '').substr(4 - all.length);
		}
		return all;
	});
	return format;
};

/**
 * 附件List集合转为Json数据
 * @param attachList
 * @returns {String}
 */
function dataConversion(attachListData){
    var jsonObjStr = "";
    var subListStr = "";
    var subListArr = "";
    attachListData = attachListData.substring(1, attachListData.length-1);
	for(;attachListData.indexOf("[") > 0;){
		subListStr = attachListData.substring(attachListData.indexOf("["), attachListData.indexOf("]") + 1);
		attachListData = attachListData.replace(subListStr, "");
	    subListStr = subListStr.substring(1, subListStr.length - 1);
	    subListArr = subListStr.split(",");
	    var subListArrLen = subListArr.length;
	    if(subListArr.length > 0){
	    	var subJsonObjStr = "";
	    	for(var i=0; i<subListArrLen; i++){
	    		var operaArr = subListArr[i].split("=");
	    		var objectName = operaArr[0];
	    		var objectValue = operaArr[1];
	    		if(i > 0){
	    			subJsonObjStr = subJsonObjStr + '\"' + objectName.substring(1, objectName.length) + '\":\"' + objectValue + '\",';
	    		}else{
	    			subJsonObjStr = '\"' + objectName + '\":\"' + objectValue + '\",';
	    		}
	    	}
	    	jsonObjStr = jsonObjStr + "{" + subJsonObjStr.substring(0, subJsonObjStr.length-1) + "}" + ", ";
	    }
	}
	jsonObjStr = "[" + jsonObjStr.substring(0, jsonObjStr.length-2) + "]";
	return JSON.parse(jsonObjStr);
}

//封装Map结构
 function Map() {
     this.keys = new Array();
     this.data = {};
     //添加键值对
     this.put = function(key, value) {
         if (this.data[key] == null) { //如键不存在则给键域数组添加键名
             this.keys.push(key);
         }
         this.data[key] = value; //给键索引对应的值域赋值
         return this;
     };
     //获取键对应的值
     this.get = function(key) {
         return this.data[key];
     };
     //去除键值，(去除键数据中的键名及对应的值)
     this.remove = function(key) {
         this.keys.remove(key);
         this.data[key] = null;
     };
     //判断键值元素是否为空
     this.isEmpty = function() {
         return this.keys.length == 0;
     };
     //获取键值元素大小
     this.size = function() {
         return this.keys.length;
     };
 }
 
 Array.prototype.indexOf = function(val) { 
	 for (var i = 0; i < this.length; i++) { 
	 if (this[i] == val) return i; 
	 } 
	 return -1; 
 };
 
 Array.prototype.remove = function(val) { 
	 var index = this.indexOf(val); 
	 if (index > -1) {
	 this.splice(index, 1); 
	 } 
 };
